package com.zzg.controller;

import java.util.ArrayList;
import java.util.List;

import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.github.pagehelper.PageInfo;
import com.zzg.author.condition.UserCondition;
import com.zzg.author.model.domain.SysRole;
import com.zzg.author.model.domain.SysUser;
import com.zzg.author.service.SysRoleService;
import com.zzg.author.service.SysUserRoleService;
import com.zzg.author.service.SysUserService;
import com.zzg.author.shrio.enums.SysUserStatusEnum;
import com.zzg.author.shrio.realm.ShiroRealm;
import com.zzg.base.response.BaseResponse;
import com.zzg.base.response.PageResponse;
import com.zzg.encryp.UsingAESUtil;
import com.zzg.util.result.ResultUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;

@Api(value = "用户",description = "用户管理")
@Controller
@RequestMapping("/user")
@Slf4j
public class UserController {
	 	@Autowired
	    private SysUserService sysUserService;
	    @Autowired
	    private SysRoleService sysRoleService;
	    @Autowired
	    private SysUserRoleService sysUserRoleService;
	    @Autowired
	    private ShiroRealm hopeShiroRealm;
	    
	    
	    /**用户列表**/
	    @ApiOperation(value = "用户列表", notes = "用户列表")
	    @RequiresPermissions("user:user:view")//默认查看权限开启
	    @GetMapping("/user")
	    public ModelAndView user(){
	        return ResultUtil.view("admin/user/user");
	    }

	    @RequiresPermissions("user:list")
	    @PostMapping("/list")
	    @ResponseBody
	    public PageResponse list(UserCondition vo){
	        PageInfo<SysUser> pageInfo=sysUserService.findPageBreakByCondition(vo);
	        return ResultUtil.tablePage(pageInfo);
	    }

	    /***
	     * 添加用户
	     * @return
	     */
	    @ApiOperation(value = "添加用户", notes = "添加用户")
	    @GetMapping("/add")
	    public ModelAndView add(){
	        return ResultUtil.view("admin/user/add");
	    }

	    @RequiresPermissions("user:add")
	    @PostMapping("/add")
	    @ResponseBody
	    public BaseResponse add(SysUser sysUserFrom,String password2){
	        SysUser user = sysUserService.getByUserName(sysUserFrom.getUsername());
	        if (ObjectUtil.isNotNull(user)) {
	            return ResultUtil.error("该用户名[" + user.getUsername() + "]已存在！请更改用户名");
	        }
	        if (!sysUserFrom.getPassword().equals(password2)) {
	            return ResultUtil.error("两次密码不相同！");
	        }
	        try {
	            sysUserFrom.setPassword(UsingAESUtil.encrypt(sysUserFrom.getPassword(),sysUserFrom.getUsername()));
	            sysUserFrom.setCreatetime(DateUtil.date());
	            sysUserFrom.setUpdatetime(DateUtil.date());
	            sysUserFrom.setUserId(RandomUtil.randomUUID().substring(0,7).toString());
	            if (ObjectUtil.isNull(sysUserFrom.getStatus())){
	                sysUserFrom.setStatus(SysUserStatusEnum.NORMAL.getCode());
	            }
	            if(!sysUserService.insert(sysUserFrom)){
	                return ResultUtil.error("用户添加失败！");
	            }
	            return ResultUtil.success("用户添加成功！");
	        }catch (Exception e){
	            log.info("[用户添加失败]-[{}]",e.getMessage());
	            return ResultUtil.error("用户添加失败！");
	        }
	    }

	    /***
	     * 用户分配角色
	     */
	    @ApiOperation(value = "用户分配角色", notes = "用户分配角色")
	    @PostMapping("/rolesWithSelected")
	    @ResponseBody
	    public BaseResponse<List<SysRole>> rolesWithSelected(Integer userId) {
	        return ResultUtil.success(null, sysRoleService.RoleListWithSelected(userId));
	    }

	    @RequiresPermissions("user:saveUserRoles")
	    @PostMapping("/saveUserRoles")
	    @ResponseBody
	    public BaseResponse<List<SysRole>> saveUserRoles(Integer userId, String roleIds) {
	        log.info("[用户id-[{}]，角色id-[{}]",userId,roleIds);
	        //添加
	        sysUserRoleService.addUserRole(userId,roleIds);
	        //更新当前登录的用户的权限缓存
	        List<String> userIds=new ArrayList<>();
	        userIds.add(Convert.convert(String.class,userId));
	        hopeShiroRealm.clearAuthorizationByUserId(userIds);
	        return ResultUtil.success("操作成功");
	    }

	    /***
	     * 删除用户
	     * @param id
	     * @return
	     */
	    @ApiOperation(value = "删除用户", notes = "删除用户")
	    @RequiresPermissions("user:delete")
	    @PostMapping("/delete/{id}")
	    @ResponseBody
	    public BaseResponse delete(@PathVariable("id") Integer id){
	        if (sysUserService.deleteById(id)){
	            return ResultUtil.success("用户删除成功！");
	        }else {
	            return ResultUtil.error("用户删除失败！");
	        }
	    }

	    /***
	     * 编辑用户
	     */
	    @ApiOperation(value = "编辑用户", notes = "编辑用户")
	    @GetMapping("/edit/{id}")
	    public ModelAndView edit(@PathVariable("id") Integer id,ModelMap map){
	        map.addAttribute("user",sysUserService.selectById(id));
	        return ResultUtil.view("admin/user/edit");
	    }

	    @RequiresPermissions("user:edit")
	    @PostMapping("/edit")
	    @ResponseBody
	    public BaseResponse edit(SysUser sysUserFrom){
	        int a=sysUserService.updateByUserId(sysUserFrom);
	        if (a>0){
	            return ResultUtil.success("用户修改成功！");
	        }else {
	            return ResultUtil.error("用户修改失败！");
	        }
	    }
}
